<?php

namespace app\api\controller\evaluation;

use app\admin\model\EvaluationElist;
use app\admin\model\EvaluationQrcode;
use app\admin\model\EvaluationTemplate;
use app\common\controller\AdminController;
use app\common\controller\ApiController;
use app\common\model\EvaluationOlist;
use app\common\model\Users;
use think\App;
use think\facade\Cache;
header('Access-Control-Allow-Origin:*');
ini_set("max_execution_time", 300);
class Elist extends  ApiController
{
    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\EvaluationElist();

    }

    /**
     * 获取微信用户信息
     * licheng 2020/6/31
     */
    public function getUserWxInfo()
    {

        $code = $_GET["code"];
        $admin_id = $_GET["admin_id"];
        $template_id = $_GET['template_id'];
        $qr_id = $_GET['qr_id'];
        $appid = 'wx6b6bf9e43755f020';
        $appkey = '3aea7042dc1717d26585e8b17f2626bf';
        # 第一步:取全局access_token

        $tokenL = Cache::get('wxToken');

        if (!$tokenL) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appkey;
            $token =$this->getJson($url);
            $tokenL = $token["access_token"];
            Cache::set('wxToken', $tokenL, 7200);

        }

        # 第二步:取得openid
        $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appkey . "&code=" . $code . "&grant_type=authorization_code";
        $oauth2 = $this->getJson($oauth2Url);

        # 第三步:根据全局access_token和openid查询用户信息
        // $access_token      = $this->getAccessToken($this->appid, $this->appkey);
        $access_token = $oauth2['access_token'];
        $openid = $oauth2['openid'];
//        $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$tokenL&openid=$openid&lang=zh_CN";
        $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $userinfo = $this->getJson($get_user_info_url);







        $users = Users::where('open_id',$userinfo['openid'])->findOrEmpty();
        if($users->isEmpty()){

            $post['reg_time']  = time();
            $post['login_count'] = 1;
            $post['open_id']  = $userinfo['openid'];
            $post['nickname'] = $userinfo['nickname'];
            $post['sex']      = $userinfo['sex'];
            $post['city']     = $userinfo['city'];
            $post['head_pic'] = $userinfo['headimgurl'];
            $post['last_ip']  = $_SERVER['REMOTE_ADDR'];
            $post['last_login'] = time();
            $users_id = Users::insert($post,true);
        }else{
            $post['login_count'] = $users->login_count +1;
            $post['open_id']  = $userinfo['openid'];
            $post['nickname'] = $userinfo['nickname'];
            $post['sex']      = $userinfo['sex'];
            $post['city']     = $userinfo['city'];
            $post['head_pic'] = $userinfo['headimgurl'];
            $post['last_ip']  = $_SERVER['REMOTE_ADDR'];
            $post['last_login'] = time();
            Users::where('users_id',$users->users_id)->update($post);
            $users_id = $users->users_id;
        }
//        $returnUrl = 'http://demo.yixuezhongyi.com/api/evaluation.elist/addEvaluate?template_id=' . $template_id .'&users_id=' . $users_id;

        $qr_user_id = EvaluationQrcode::where('id',$qr_id)->value('qr_user_id');
        $evaluationElist = EvaluationElist::where('qr_id',$qr_id)->where('users_id',$users_id)->find();
        if(!empty($evaluationElist)){
            $returnUrl = 'http://' .$_SERVER['HTTP_HOST'] .'/h5/zhuiping.html?template_id=' . $template_id .'&users_id=' . $users_id. '&qr_user_id=' . $qr_user_id .'&qr_id='. $qr_id;
        }else{
            $returnUrl = 'http://'. $_SERVER['HTTP_HOST'] . '/h5/?template_id=' . $template_id .'&users_id=' . $users_id. '&qr_user_id=' . $qr_user_id .'&qr_id='. $qr_id;
        }

        if(isset($_GET['evl']) && $_GET['evl'] == 1){
            $returnUrl = 'http://'. $_SERVER['HTTP_HOST'] . '/h5/?template_id=' . $template_id .'&users_id=' . $users_id. '&qr_user_id=' . $qr_user_id.'&qr_id='. $qr_id;
        }

        echo "<script>window.location.href='$returnUrl'</script>";


    }

    /**
     * 发票评价
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addEvaluate()
    {


        if ($this->request->isPost()) {
            $post = $this->request->post();

            $qrInfo = EvaluationQrcode::find($post['qr_id']);
            if(!in_array($post['student_name'],$qrInfo['student_arr']) && $qrInfo['is_check']){
                echo  json_encode(['code'=>1,'msg'=> '校验学生姓名不存在']);exit;
            }

            $post['template_id'] = EvaluationQrcode::where('id',$post['qr_id'])->value('template_id');
            $row = EvaluationTemplate::find($qrInfo['template_id']);

            if(date('Y-m-d') > explode(' - ', $qrInfo['evaluate_period_time'])[1]){


               echo  json_encode(['code'=>1,'msg'=>'评价时间:' . $qrInfo['evaluate_period_time'] .'，目前已截止']);exit;
            }

            $post['admin_id'] = $post['qr_user_id'];

            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                echo json_encode(['code'=>1,'msg'=>$e->getMessage()]);exit;
            }
            echo $save ? json_encode(['code'=>0,'msg'=>'感谢评价']) : json_encode(['code'=>1,'msg'=>'保存失败']);exit;
        }


    }
    function getJson($url, $data = '',$request_way = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if (isset($data) && $data) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        if ($request_way) {

            curl_setopt($ch, CURLOPT_POST, 1);
        }

        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

    //原文链接：https://blog.csdn.net/qq_24909089/article/details/97527008

    /**
     * 上传图片、视频
     * @return void
     */
    public function fileUpload()
    {
        //限制类型数组
        $type_arr = [
            'image/gif',
            'image/jpeg',
            'image/png',
            'video/mp4',
        ];
        $file    = !empty($_FILES["file"]) ? $_FILES["file"] : ""; //文件
        //以日期为区间划分文件夹
        if($file["type"] =='video/mp4' ){

            $up_dir = ROOT_PATH . 'public'.DS.'uploads'.DS.'video'.DS.date('Ymd');    //分片合并存放目录
            $returnPath = 'uploads'.DS.'video'.DS.date('Ymd');//返回路径
        }else{
            $up_dir = ROOT_PATH . 'public'.DS.'uploads'.DS.'image'.DS.date('Ymd');    //分片合并存放目录
            $returnPath = 'uploads'.DS.'image'.DS.date('Ymd');//返回路径
        }

        if (!file_exists($up_dir)) {
            mkdir($up_dir, 0777, true); //不存在创建文件夹
            chmod($up_dir, 0777); //强制赋予权限
        }

        if (in_array($file["type"], $type_arr)) {

            if ($file["error"] > 0) {

                 $res = array('code' => '101', 'msg' => $file["error"]);

            } else {

                //大于10m 不存储
                if (($file["size"] / 1048576) > 20) {
                     $res = array('code' => '406', 'msg' => '文件过大，上限20m!');
                }

                //获取后缀
                $name      = explode('/', $file["type"]);
                $file_name = $up_dir . DS . date('YmdHis', time()) . '.' . $name[1];
                $returnPath = $returnPath . DS . date('YmdHis', time()) . '.' . $name[1];
                if (file_exists($file_name)) {

                     $res = array('code' => '406', 'msg' => '文件已存在!');

                } else {
                    move_uploaded_file($file["tmp_name"], $file_name);

                    $res = array('code' => '0', 'msg' => '上传成功!', 'path' => 'http://'.$_SERVER['HTTP_HOST']. DS. $returnPath);

                }
            }
        } else {

             $res = array('code' => '104', 'msg' => '无效的文件类型!');
        }

        echo json_encode($res);

    }

    /**
     * 历史记录
     * @return void
     */
    public function recordList($users_id)
    {
        $list = EvaluationElist::where('users_id',$users_id)->order('id','desc')->select();
        $res = array('code' => '0', 'msg' => '上传成功!', 'data' => $list);
        echo json_encode($res);
    }


    //模拟传输数据
    public function transEvalData()
    {
//        $url = 'http://127.0.0.1:8000/api/evaluation.elist/receiveEvalData';
        $url = 'http://demo.yixuezhongyi.com/api/evaluation.elist/receiveEvalData';
        $list = EvaluationElist::where('id',102)->select()->toArray();
        $arrInput = json_encode($list);
        $data = $this->http_post($url, $arrInput, 5);
        echo $data;
    }

    public function http_post($url,$post,$timeout){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'Content-Type' => 'application/json',
        ]);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);

        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        $code  = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $errMsg= curl_multi_getcontent($curl);
        curl_close($curl);
    }

    //日志记录
    function logger($log_content)
    {
        $max_size = 100000;
        $path = ROOT_PATH . 'public';
        $log_filename = $path . DS ."raw.log";

        if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
        file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
    }
    /**
     *	php之间的post方法
     *
     *
     */
    public function send_post($url, $post_data){
//        $post_data = array(
//            'type'=>3,
//            'goods_name'=>'423',
//            'mobile'=>'321321'
//        );
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return $result;
    }




    public function getStudentInfo($users_id,$template_id,$qr_user_id){
        $class_name = EvaluationQrcode::where('template_id',$template_id)->where('qr_user_id',$qr_user_id)->value('class_name') ?? '';
        $student_name = EvaluationElist::where('student_name','<>','')->where('users_id',$users_id)->value('student_name') ?? '';
        $student_arr = EvaluationQrcode::where('template_id',$template_id)->where('qr_user_id',$qr_user_id)->value('student_arr') ?? '';
        echo json_encode(array('code'=>0,'msg'=>'操作成功','data'=>['class_name'=>$class_name,'student_name'=>$student_name,'student_arr'=>$student_arr]));
    }

    /**
     * Notes: 接受旧数据
     * author: bxm
     * Date: 2023/2/21
     * Time: 9:26
     * @return false|string
     */
    public function receiveEvalData()
    {

        try{
            header('Content-type: application/json');
            $postStr = file_get_contents('php://input');


            //方倍工作室

            $this->logger('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].(empty($_SERVER['QUERY_STRING'])?"":("?".$_SERVER['QUERY_STRING'])));
            $this->logger($postStr);

            $arr = json_decode($postStr,true);
            $this->yanzSigin($arr);

            EvaluationOlist::insertAll($arr);
        }catch (\Exception $e){
            return json_encode(['code'=>1, 'msg'=> $e->getMessage()]);
        }


        return  json_encode(['code'=>0,'msg'=>'接受成功','data'=>[]]);
    }


    /**
     * Notes: 获取所有评价信息 By openid
     * author: bxm
     * Date: 2023/2/18
     * Time: 14:05
     * @param $openid
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAllEvalDataByOpenid()
    {
        try{
            $data = [];
            $post = request()->post();
            $this->yanzSigin($post);

            $userInfo = Users::where('open_id',$post['data']['openid'])->field('users_id,open_id,union_id,nickname,head_pic,sex,reg_time,last_login,last_ip')->find();
            if(!empty($userInfo)){
                $users_id = $userInfo->users_id;

                $data['user_info'] = $userInfo;
                $list = EvaluationElist::with(['evaluationTemplate','systemAdmin'])->where('users_id',$users_id)->select();
                $data['list'] = $list;
            }
        }catch (\Exception $e){
            return json_encode(['code'=>1, 'msg'=> $e->getMessage()]);
        }


        return json_encode(['code'=>0,'msg'=>'操作成功','data'=>$data]);
    }
}